package com.makao.controller;

import java.net.URI;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

@RestController
public class Controller {
	@Autowired
	private EurekaClient discoveryClient;

    @RequestMapping("/sentence")
    public  String getSentence() {
        return
                getWord("cloud-eureka-client-subject") + " "
                        + getWord("cloud-eureka-client-verb") + " "
                        + getWord("cloud-eureka-client-object") + "."
                ;//大小写不区分
    }

    public String getWord(String service) {
        List<ServiceInstance> list = discoveryClient2.getInstances(service);
        if (list != null && list.size() > 0 ) {
            URI uri = list.get(0).getUri();
            if (uri !=null ) {
                return (new RestTemplate()).getForObject(uri,String.class);
            }
        }
        return null;
    }
    
    @RequestMapping("/sentence2")
    public  String getSentence2() {
        return
                getWord("cloud-eureka-client-subject") + " "
                        + getWord("cloud-eureka-client-verb") + " "
                        + getWord("cloud-eureka-client-object") + "."
                ;//大小写不区分
    }
    
    public String getWord2(String service) {
        List<ServiceInstance> list = discoveryClient2.getInstances(service);
        if (list != null && list.size() > 0 ) {
            URI uri = list.get(0).getUri();
            if (uri !=null ) {
                return (new RestTemplate()).getForObject(service,String.class);//直接使用服务名，即spring。application。name都可以调用，这是服务名即是虚拟ip
            }
        }
        return null;
    }
    
	@Autowired
	private DiscoveryClient discoveryClient2;
	@RequestMapping(value="/eureka-info",method=RequestMethod.GET)
	public URI serviceUrl2() {
		System.out.println(discoveryClient2);
	    List<ServiceInstance> list = discoveryClient2.getInstances("cloud-eureka-server");
	    if (list != null && list.size() > 0 ) {
	        return list.get(0).getUri();
	    }
	    return null;
	}
    
    @GetMapping("/eureka-instance")
    public String serviceUrl() {
        InstanceInfo instance = discoveryClient.getNextServerFromEureka("CLOUD-EUREKA-CLIENT-CONSUMER", false);
        return instance.getHomePageUrl();
    }
}